package com.cy.aircompressor.main.home.fragment.provider;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentManager;

import com.cy.aircompressor.databinding.ItemNewVibrationChangeTrendBinding;
import com.cy.aircompressor.entity.linechart.LineChartEntry;
import com.cy.aircompressor.entity.sensor.SensorBgg;
import com.cy.aircompressor.entity.sensor.SensorItemData;
import com.cy.aircompressor.entity.sensor.SensorLineChartData;
import com.cy.aircompressor.entity.sensor.SensorLatestData;
import com.cy.aircompressor.entity.sensor.SensorStatisticsData;
import com.cy.aircompressor.main.home.dialog.LineChartFullScreenDialogV2;
import com.cy.aircompressor.main.ui.onlinemonitor.utils.LineChartUtil;
import com.drug.lib.view.recycptr.ItemViewBinder;
import com.github.mikephil.charting.data.Entry;
import com.jakewharton.rxbinding2.view.RxView;
import com.net.model.base.BaseBindViewHolder;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class SpeedRmsProvider extends ItemViewBinder<SensorLineChartData, SpeedRmsProvider.ViewHolder> {


    Context mContext;
    FragmentManager fragmentManager;
    public SpeedRmsProvider(FragmentManager fragmentManager, Context mContext) {
        this.mContext = mContext;
        this.fragmentManager = fragmentManager;
    }

    @NonNull
    @Override
    protected SpeedRmsProvider.ViewHolder onCreateViewHolder(@NonNull LayoutInflater inflater, @NonNull ViewGroup parent) {
        return new ViewHolder(ItemNewVibrationChangeTrendBinding.inflate(inflater, parent, false));
    }

    @Override
    protected void onBindViewHolder(@NonNull SpeedRmsProvider.ViewHolder holder, @NonNull SensorLineChartData entity) {

        holder.mBinding.switchBtn.setText(entity.isSpeed() ? "切换speed曲线" : "切换rms曲线");
        setDefault(holder, entity);
        setRealTimeData(holder, entity);
        loadLineChart(holder, entity);
        RxView.clicks(holder.mBinding.switchBtn)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    entity.setSpeed(!entity.isSpeed());
                    holder.mBinding.switchBtn.setText(entity.isSpeed() ? "切换speed曲线" : "切换rms曲线");
                    setRealTimeData(holder, entity);
                    loadLineChart(holder, entity);
                });
        RxView.clicks(holder.mBinding.fullScreen)
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(o -> {
                    LineChartFullScreenDialogV2.showDialogFragment(fragmentManager, "speedrms", entity);
                });
    }

    private void loadLineChart(ViewHolder holder, @NonNull SensorLineChartData entity) {
        SensorBgg sensorBgg = entity.getSensorBgg();
        if (sensorBgg != null) {
            List<SensorStatisticsData> sensorStatisticsData = sensorBgg.getSensorStatisticsData();
            if (sensorStatisticsData != null && sensorStatisticsData.size() != 0) {
                stowageData(holder, sensorBgg, entity.isSpeed());
            } else {
                LineChartUtil.addEmptyLine(holder.mBinding.lineChart);
            }
        } else {
            LineChartUtil.addEmptyLine(holder.mBinding.lineChart);
        }
        LineChartUtil.checkLineChart(holder.mBinding.lineChart);
    }

    private void stowageData(ViewHolder holder, SensorBgg sensorBgg, boolean isSpeed) {
        List<Entry> entrieX = new ArrayList<>();
        List<Entry> entrieY = new ArrayList<>();
        List<Entry> entrieZ = new ArrayList<>();
        List<SensorStatisticsData> sensorStatisticsData = sensorBgg.getSensorStatisticsData();
        for (int i = 0; i < sensorStatisticsData.size(); i++) {
            SensorStatisticsData statisticsData = sensorStatisticsData.get(i);
            long time = getDate(statisticsData.getRt());
            if (isSpeed) {
                Entry entry = new Entry(i, statisticsData.getXspeed(), time);
                entrieX.add(entry);

                entry = new Entry(i, statisticsData.getYspeed(), time);
                entrieY.add(entry);

                entry = new Entry(i, statisticsData.getZspeed(), time);
                entrieZ.add(entry);

            } else {
                Entry entry = new Entry(i, statisticsData.getXrms(), time);
                entrieX.add(entry);

                entry = new Entry(i, statisticsData.getYrms(), time);
                entrieY.add(entry);

                entry = new Entry(i, statisticsData.getZrms(), time);
                entrieZ.add(entry);

            }
        }
        LineChartEntry xLineChartEntry = sensorBgg.getxLineChartEntry();
        xLineChartEntry.setEntrys(entrieX);
        xLineChartEntry.setColor(getColor("x"));
        LineChartEntry yLineChartEntry = sensorBgg.getyLineChartEntry();
        yLineChartEntry.setEntrys(entrieY);
        yLineChartEntry.setColor(getColor("y"));
        LineChartEntry zLineChartEntry = sensorBgg.getzLineChartEntry();
        zLineChartEntry.setEntrys(entrieZ);
        zLineChartEntry.setColor(getColor("z"));

        List<LineChartEntry> lineChartEntries = new ArrayList<>();
        lineChartEntries.add(xLineChartEntry);
        lineChartEntries.add(yLineChartEntry);
        lineChartEntries.add(zLineChartEntry);
        LineChartUtil.addAndUpdateLine(holder.mBinding.lineChart, lineChartEntries);

    }

    private long getDate(String rt) {
        Date date = null;
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            date = format.parse(rt);
            return date.getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return 0;
    }

    /**
     * 设置最新数据
     *
     * @param holder
     * @param entity
     */
    private void setRealTimeData(ViewHolder holder, SensorLineChartData entity) {
        SensorLatestData sensorLatestData = entity.getSensorLatestData();
        if (sensorLatestData == null) {
            holder.mBinding.xValue.setText("-");
            holder.mBinding.yValue.setText("-");
            holder.mBinding.zValue.setText("-");
        } else {
            SensorItemData sensorItemData = getSensorItemData("body", entity.getPointCode(), sensorLatestData.getDataList());
            if (sensorItemData == null) {
                holder.mBinding.xValue.setText("-");
                holder.mBinding.yValue.setText("-");
                holder.mBinding.zValue.setText("-");
                return;
            }
            double Xspeed = sensorItemData.getXspeed();
            double Yspeed = sensorItemData.getYspeed();
            double Zspeed = sensorItemData.getZspeed();

            double Xrms = sensorItemData.getXrms();
            double Yrms = sensorItemData.getYrms();
            double Zrms = sensorItemData.getZrms();

            holder.mBinding.xValue.setText(String.valueOf(entity.isSpeed() ? Xspeed : Xrms));
            holder.mBinding.yValue.setText(String.valueOf(entity.isSpeed() ? Yspeed : Yrms));
            holder.mBinding.zValue.setText(String.valueOf(entity.isSpeed() ? Zspeed : Zrms));
        }
    }

    private SensorItemData getSensorItemData(String partCode, String pointCode, List<SensorItemData> dataList) {
        if (dataList == null)
            return null;
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
            List<SensorItemData> sensorItemDataList = dataList.stream()
                    .filter(new Predicate<SensorItemData>() {
                        @Override
                        public boolean test(SensorItemData sensorItemData) {
                            return TextUtils.equals(sensorItemData.getCompressorPartCode(), partCode) &&
                                    TextUtils.equals(sensorItemData.getCompressorPointCode(), pointCode);
                        }
                    }).collect(Collectors.toList());
            if (sensorItemDataList != null && sensorItemDataList.size() > 0) {
                return sensorItemDataList.get(0);
            }
        }
        return null;

    }


    /**
     * 设置默认值
     *
     * @param holder
     * @param entity
     */
    private void setDefault(ViewHolder holder, SensorLineChartData entity) {
        switch (entity.getPointCode()) {
            case "vibration1":
                holder.mBinding.titleName.setText("机身震动变化趋势");
                break;
            case "vibration2":
                holder.mBinding.titleName.setText("一级气缸震动变化趋势");
                break;
            case "vibration3":
                holder.mBinding.titleName.setText("二三级气缸震动变化趋势");
                break;
        }
    }

    private String getColor(String shaft) {
        switch (shaft) {
            case "x":
                return "#CF931F";
            case "y":
                return "#CF1F5E";
            case "z":
                return "#1F66CF";
            default:
                return "#FFFFFF";
        }
    }

    public class ViewHolder extends BaseBindViewHolder<ItemNewVibrationChangeTrendBinding> {

        protected ViewHolder(ItemNewVibrationChangeTrendBinding itemView) {
            super(itemView);
            LineChartUtil.initLineChart(mBinding.lineChart, false);
        }
    }


}
